package vg.modules.util_plugins;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Observable;

import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

import vg.services.graph_view_manager.interfaces.graph_view.AGraphView;
import vg.services.graph_view_manager.interfaces.tab.ATab;
import vg.services.plugin_manager.event_and_request.event.AUIEvent;
import vg.services.plugin_manager.event_and_request.event.UIEventChangeTab;
import vg.services.plugin_manager.interfaces.IPlugin;
import vg.services.plugin_manager.realization.PluginParameter;
import vg.services.user_interface_manager.interfaces.AMenuItem;

public class UndoRedoButtonPlugin implements IPlugin{
	private JMenuItem redoMenuItem, undoMenuItem;
	private PluginParameter param;
	private AGraphView view;
	//-------------------------------------------
	public void install(PluginParameter param) throws Exception {
		this.param = param;
		this.view  = null;
		this.redoMenuItem = new JMenuItem("Redo");
		this.undoMenuItem = new JMenuItem("Undo");
		//---------------------------------------
		this.redoMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(view != null) {
					view.getHighLevelGraphEditor().redo();
				}
			}
		});
		this.undoMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(view != null) {
					view.getHighLevelGraphEditor().undo();
				}
			}
		});
		this.undoMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_DOWN_MASK));
		this.redoMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, KeyEvent.CTRL_DOWN_MASK));
		//---------------------------------------
		this.param.userInterface.addMenuItem(new AMenuItem(this.undoMenuItem) {
			public void update(Observable o, Object arg) {
				changeView(arg);				
			}
		}, "edit");
		this.param.userInterface.addMenuItem(new AMenuItem(this.redoMenuItem) {
			public void update(Observable o, Object arg) {
				changeView(arg);
			}
		}, "edit");
	}
	private void changeView(Object obj) {
		if(obj==null) return;
		if(obj instanceof AUIEvent) {
			AUIEvent event = (AUIEvent)obj;
			switch(event.getType()) {
				case DEF_CHANGE_TAB: {
					UIEventChangeTab bufEvent = (UIEventChangeTab)event;
					ATab tab = bufEvent.getTab();
					if (tab != null) {
						switch (tab.getTabType()) {
							case ATab.DEF_GRAPH_VIEW_TAB_TYPE: {
								view = (AGraphView)tab;
								break;
							}							
						}
					}
					break;
				}
				
				default:break;
			}
		}
	}
}
